package com.wiki.KBS.services;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wiki.KBS.domian.Doc;
import com.wiki.KBS.domian.DocExample;
import com.wiki.KBS.mapper.DocMapper;
import com.wiki.KBS.request.DocReq;
import com.wiki.KBS.request.DocSaveReq;
import com.wiki.KBS.response.DocQueryResp;
import com.wiki.KBS.response.PageResp;
import com.wiki.KBS.utils.CopyUtil;
import com.wiki.KBS.utils.SnowFlake;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Slf4j
@Service
public class DocService {

    @Autowired
    private DocMapper docMapper;
    @Autowired
    private SnowFlake snowFlake;

    public List<DocQueryResp> docAll(){
        DocExample docExample = new DocExample();
        docExample.setOrderByClause("sort asc");    // 设置排序条件
        // 把查询结果存入Doc类型的列表里面
        List<Doc> docList = docMapper.selectByExample(docExample);
        List<DocQueryResp> docQueryResps = CopyUtil.copyList(docList, DocQueryResp.class);

        return  docQueryResps;
    }


    public PageResp<DocQueryResp> docList(DocReq req){
        DocExample docExample = new DocExample();
        docExample.setOrderByClause("sort asc");    // 设置排序条件
        //  创建查询条件
        DocExample.Criteria criteria = docExample.createCriteria();

        // 把查询结果存入Doc类型的列表里面
        PageHelper.startPage(req.getPage(), req.getSize());
        List<Doc> docList = docMapper.selectByExample(docExample);
        List<DocQueryResp> docQueryResps = CopyUtil.copyList(docList, DocQueryResp.class);

        // 查询页面信息
        PageInfo<Doc> PageInfo = new PageInfo<>(docList);
        log.info("总行数：{}",PageInfo.getTotal());
        log.info("总页数：{}",PageInfo.getPages());

        PageResp<DocQueryResp> PageResp = new PageResp<>();
        PageResp.setTotal(PageInfo.getTotal());
        PageResp.setList(docQueryResps);
        return  PageResp;
    }

    /**
     * 保存
     */
    public void save(DocSaveReq req) {
        Doc doc = CopyUtil.copy(req, Doc.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            // 新增
            doc.setId(snowFlake.nextId());
            docMapper.insert(doc);
        } else {
            // 更新
            log.info("总行数：{}",doc);
            docMapper.updateByPrimaryKey(doc);
        }
    }

    public void delete(Long id) {
        docMapper.deleteByPrimaryKey(id);
    }

    public void delete(List<Long> ids) {
        DocExample docExample = new DocExample();
        //  创建查询条件
        DocExample.Criteria criteria = docExample.createCriteria();
        criteria.andIdIn(ids);
        // 根据某一个条件来删除
        docMapper.deleteByExample(docExample);
    }
}
